const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const error = require("koa-json-error")
const parameter = require("koa-parameter")
const koaBody = require('koa-body')
const logger = require('koa-logger')
const routing = require("./routes")
const mongoose = require("mongoose")
const path = require("path")
const cors = require("koa2-cors")
const { dbs } = require('./conifig/config')
// error handler
onerror(app)
// error response to json
app.use(error({
  postFormat: (err, { stack, ...rest }) =>
    process.env.NODE_ENV === "production" ? rest : { stack, ...rest }
}))
// middlewares
app.use(cors())
app.use(require('koa-static')(__dirname + '/public'))
app.use(koaBody({
  multipart: true,    // 启用文件的接收
  formidable: {
    uploadDir: path.join(__dirname, "/public/uploads"),
    keepExtensions: true,
    maxFileSize: 10 * 1024 * 1024
  }
}))
// params check
app.use(parameter(app))

app.use(json())
app.use(logger())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

mongoose.connect(dbs, {
  useNewUrlParser: true
})

// routes
routing(app)

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
